package cn.school.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.school.entity.AjaxResult;
import cn.school.entity.Page;
import cn.school.entity.Student;
import cn.school.service.StudentService;
import cn.school.util.StringKit;

/**
 * Servlet implementation class MainServlet
 */
//@WebServlet("/*")
//不能以/开头
@WebServlet("*.do") // login.do ,update.do, admin/del.do
//   /do/*
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	StudentService studentService = new StudentService();

	protected Page<Student> studentsearch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.setContentType("application/json;charset=utf-8");

		String name = StringKit.convertNull(request.getParameter("sname"));
		String tel = StringKit.convertNull(request.getParameter("tel"));
		Date start = StringKit.toDate(request.getParameter("datestart"));
		Date end = StringKit.toDate(request.getParameter("dateend"));

		int pageNo = StringKit.toInt(request.getParameter("page"), 1);
		int pageSize = StringKit.toInt(request.getParameter("limit"), Page.PAGE_SIZE);

		Page<Student> p = studentService.paging(pageNo, pageSize, name, tel, start, end);
		return p;
	}

	protected AjaxResult studentGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		long stuno = StringKit.toLong(request.getParameter("stuno"));

		Student p = studentService.get(stuno);
		if (p == null)
			return AjaxResult.error("对象已经不存在");
		return AjaxResult.success(p);
	}

	protected AjaxResult delStudent(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		long stuno = StringKit.toLong(request.getParameter("stuno"));
		////// ???

		return AjaxResult.success(">??");
	}
//	protected void login(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		System.out.println("This is login");
//	}
//
//	protected void update(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		System.out.println("This is update");
//	}
//
//	protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		System.out.println("This is del");
//	}
//
//	protected void admin(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		System.out.println("This is admin");
//	}
//
//	protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		System.out.println("This is add");
//	}

	// 方法有返回结果，转换成json发到前端
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.setContentType("text/html;charset=utf-8");
		response.setContentType("application/json;charset=utf-8");

		PrintWriter out = response.getWriter();// .append("Served at: ").append(request.getContextPath());
//		out.print("<html>");
//		out.print("<body>");
//		out.print("<h1>");
//		out.print("contextpath:" + request.getContextPath());
		String path = request.getServletPath();
		path = path.substring(1, path.length() - 3);
		if (path.equals("doGet") || path.equals("doPost") || path.equals("service")) {
			response.sendError(405, "方法禁止执行");
			return;
		}
		try {
			Method m = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
			Object o = m.invoke(this, request, response);
			if (o != null) {
				String str = JSON.toJSONStringWithDateFormat(o, "yyyy-MM-dd", SerializerFeature.WriteNullStringAsEmpty,
						SerializerFeature.WriteMapNullValue);
				response.getWriter().print(str);
			}
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
			response.sendError(500, "方法没有找到");
		} catch (Exception e) {
			e.printStackTrace();
			response.sendError(500, "执行出错");
		}

//		out.print("</h1>");
//		out.print("<h1 style='color:red;font-size:90px;'>");
//		out.print("servletpath:" + request.getServletPath());
//		if (path.equals("login")) {
//			out.print("这是登录操作");
//			login(request, response);
//		} else if (path.equals("add")) {
//			out.print("这是增加操作");
//			add(request, response);
//		} else if (path.equals("update")) {
//			out.print("这是修改操作");
//			update(request, response);
//		} else if (path.equals("del")) {
//			out.print("这是删除操作");
//			del(request, response);
//		} else {
//			out.print("这是未知操作");
//		}
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("URL:" + request.getRequestURL());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("URI:" + request.getRequestURI());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("query string:" + request.getQueryString());
//		out.print("</h1>");
//		out.print("<h1>");
//		out.print("server info:协议：" + request.getScheme() + ",地址：" + request.getRemoteHost() + ","
//				+ request.getLocalPort());
//		out.print("</h1>");
//		out.print("</body>");
//		out.print("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
